import { NzMessageService } from 'ng-zorro-antd/message';
import { UserService } from '@service/user.service';
import { AbsFormUtil } from '@abstract/form';
import { Component, Input, OnInit } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { deepClone } from '@utils/lang';
import { NzModalRef } from 'ng-zorro-antd/modal';

@Component({
	selector: 'app-user-index-edit',
	templateUrl: './user-index-edit.component.html',
	styleUrls: ['./user-index-edit.component.less']
})
export class UserIndexEditComponent extends AbsFormUtil implements OnInit {
	@Input() item: any;
	warehouseNodes = [];
	nzLoading = false;
	toolTypeList = [];

	constructor(
		private fb: FormBuilder,
		private nzModalRef: NzModalRef,
		private nzMessageService: NzMessageService,
		private userService: UserService
	) {
		super();
	}

	ngOnInit() {
		this.buildForm();
	}
	private patchItem() {
		if (this.item) {
			const userItem = this.item;
			if (userItem?.warehouses?.length) {
				userItem.warehouseIdList = userItem.warehouses.map(it => it.id);
			}
			if (userItem?.types?.length) {
				userItem.typeIdList = userItem.types.map(it => it.id);
			}
			this.validateForm.patchValue(userItem);
		}
	}

	// private getTypeId(typeItem, result: string[]) {
	// 	const item = this.toolTypeList.find(itm => itm.id === typeItem.parentId);
	// 	if (item) {
	// 		result.unshift(item.id);
	// 		if (item.parentId) {
	// 			return this.getTypeId(item, result);
	// 		}
	// 		return result;
	// 	}
	// }
	async checkUser() {
		const userCode = this.getFormControl('code').value;
		if (!userCode) {
			this.nzMessageService.warning("请填写用户编码");
			return;
		}
		this.nzLoading = true;
		const result = await this.userService.checkUser(userCode);
		const val = Object.values(result).filter(Boolean);
		if (!val?.length) {
			this.nzMessageService.info('无该用户编码数据');
			this.nzLoading = false;
			return;
		}
		this.validateForm.patchValue(result);
		setTimeout(() => {
			this.nzLoading = false;
		}, 500);
	}
	destroyModal() {
		this.nzModalRef.destroy();
	}

	private changeWarehouse(toolTypeOpt: any[]) {
		toolTypeOpt.forEach(it => {
			it.isLeaf = !it.hasChildrenFlag;
			it.value = it.id;
			it.title = it.name;
			it.key = it.id;
			if (it?.children?.length) {
				this.changeWarehouse(it.children);
			}
		})
	}
	onSubmit() {
		this.markAsDirty();
		if (this.validateForm.invalid) {
			return;
		}
		const resFormVal = deepClone(this.validateForm.value);
		return { ...resFormVal };
	}
	buildForm() {
		this.validateForm = this.fb.group({
			code: ['', [Validators.required]],
			name: ['', [Validators.required]],
			deptName: ['', [Validators.required]],
			email: ['', [Validators.required]],
			forbidden: [false, [Validators.required]],
			warehouseIdList: [[]],
			typeIdList: [[]],

		});
	}


}
